package org.jsbd.boss.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsbd.boss.dao.IExtractingDataDao;
import org.jsbd.boss.service.IExtractingDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("extractingData")
public class ExtractingDataServiceImpl implements IExtractingDataService{
	private static final Logger LOGGER=LoggerFactory.getLogger(ExtractingDataServiceImpl.class);
	@Autowired
    private IExtractingDataDao extractingDataDao;
	
	@Override
	public Map<String, Object> getExtractData(int page, int rows, String tableName, String startTime, String endTime) {
		/*String dbName = extractingDataDao.getDbByTableName(tableName);
		if (StringUtils.isBlank(dbName)) {
			return null;
		}*/
		Map<String, Object> result = new HashMap<>();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tableName", tableName);
		param.put("start", (page-1) * rows);
		param.put("length", rows);
		param.put("startTime", startTime);
		param.put("endTime", endTime);
		
		Integer total;
		try {
			total = extractingDataDao.getTablesDatasCount(param);
			if (total != 0) {
				List<Map<String, Object>> dataList = extractingDataDao.getTablesDatas(param);
				for (Map<String, Object> data : dataList) {
				  try {
						if (data.containsKey("create_time") && data.get("create_time") != null) {
						    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						    String tsStr = sdf.format(data.get("create_time"));
						    data.put("create_time", tsStr);
						}
					} catch (Exception e) {
						LOGGER.error("",e);
					}
				}
				result.put("data", dataList);
			} else {
				result.put("data", new ArrayList<>());
			}
			result.put("total", total);
			Integer totalPage = (total%rows == 0) ? total/rows : total/rows+1;
			result.put("totalPage", totalPage);
			return result;
		} catch (Exception e) {
			LOGGER.error("",e);
			return null;
		}
		
	}

}
